<?php
// +----------------------------------------------------------------------
// | Qbt CMS Plugin
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2018 http://www.qbt8.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 黄老邪 <develop02@qbt8.com>
// +----------------------------------------------------------------------
namespace plugins\qbt_app_update\controller;
use cmf\controller\PluginAdminBaseController;
use plugins\qbt_app_update\controller\ApkarserController;
use think\Db;

class AdminIndexController extends PluginAdminBaseController
{
    private $path;
    public function _initialize()
    {
        $this->data = input();
        $this->apkarser = new ApkarserController();
        $adminId = cmf_get_current_admin_id();//获取后台管理员id，可判断是否登录
        $this->path = str_replace("\\",DS,dirname(dirname(dirname(__DIR__))));

        if (!empty($adminId)) {
            $this->assign("admin_id", $adminId);
        } else {
            $this->error('未登录');
        }
    }

    /**
     * app更新
     * @adminMenu(
     *     'name'   => 'app更新',
     *     'parent' => 'admin/Plugin/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '千佰特app更新管理',
     *     'param'  => ''
     * )
     */
    //首页
    public function index(){
        $lists = Db::name('app_update')->paginate(10);
        $this->assign('lists', $lists->items());
        $this->assign('page',$lists->render());
        return $this->fetch('/index');
    }

    //增加页
    public function add(){
        return $this->fetch('/add');
    }

    //添加程序
    public function add_post(){
        $param = $this->data;
        $sql_data = [];
        if($param['type'] == 1){
            //获取apk相关信息
            $this->have_data($param['iden'],'api标识已经存在');
            $this->isset_data('apk文件不能为空');
            $file_name = $this->upload_app();
            $file_name1 = './upload/'.$file_name;//dump($file_name1);return;
            if(!empty($param['app_name'])){
                $this->empty_data($param['iden'],'api标识不能为空');
                $this->empty_data($param['app_name'],'名称不能为空');
                $this->empty_data($param['packge_name'],'包名不能为空');
                $this->empty_data($param['version_name'],'版本名称不能为空');
                $this->empty_data($param['version_code'],'版本号不能为空');
                $sql_data['app_name'] = $param['app_name'];
                $sql_data['version_code'] = $param['version_code'];
                $sql_data['packge_name'] = $param['packge_name'];
                $sql_data['version_name'] = $param['version_name'];
            }else{
                $this->empty_data($param['iden'],'api标识不能为空');
                $sql_data = $this->app_info($file_name1);
                if(empty($sql_data['app_name'])){$this->error('上传文件有误');}
            }
            $this->empty_data($param['upgrade_point'],'更新备注不能为空');
            $sql_data['apk_url'] = $file_name;
        }else{

            $this->have_data($param['iden'],'api标识已经存在');
            $this->empty_data($param['iden'],'api标识不能为空');
            $this->empty_data($param['app_name1'],'名称不能为空');
            $this->empty_data($param['version_code1'],'版本号不能为空');


            $this->empty_data($param['upgrade_point'],'更新备注不能为空');
            $sql_data['app_name'] = $param['app_name1'];
            $sql_data['version_code'] = $param['version_code1'];
            if($param['type'] == 2){
                $this->empty_data($param['apk_url'],'版本更新地址不能为空');
                $sql_data['apk_url'] = $param['apk_url'];
            }

        }
        //重组数据准备入库
        $sql_data['type'] = $param['type'];
        $sql_data['force'] = isset($param['force'])?1:0;
        $sql_data['iden'] = $param['iden'];
        $sql_data['upgrade_point'] = $param['upgrade_point'];
        $sql_data['create_time'] = time();
        $status = Db::name('app_update')->insert($sql_data);

        $this->data_action($status,'add');
    }

    //详情页
    public function info()
    {
        $id = $this->data['id'];
        $info = Db::name('app_update')->where('id =' . $id)->find();
        $info['apk_url'] = cmf_get_file_download_url($info['apk_url']);
        $this->assign('info', $info);
        return $this->fetch('/info');
    }

    //后台更新页
    public function edit_post(){
        $param = $this->data;
        $sql_data = [];
        if($param['type'] == 1){
            //获取apk相关信息
            if(!empty($_FILES)){
                $file_name = $this->upload_app();
                if($file_name){
                    $sql_data['apk_url'] = $file_name; $file_name1 = './upload/'.$file_name;
                }
            }
            if(!empty($param['app_name'])){
                $this->empty_data($param['iden'],'api标识不能为空');
                $this->empty_data($param['app_name'],'名称不能为空');
                $this->empty_data($param['packge_name'],'包名不能为空');
                $this->empty_data($param['version_name'],'版本名称不能为空');
                $this->empty_data($param['version_code'],'版本号不能为空');
                $sql_data['app_name'] = $param['app_name'];
                $sql_data['version_code'] = $param['version_code'];
                $sql_data['packge_name'] = $param['packge_name'];
                $sql_data['version_name'] = $param['version_name'];//dump($file_name1);return;
            }else{
                $this->empty_data($param['iden'],'api标识不能为空');
                $sql_data = $this->app_info($file_name1);

                if(empty($sql_data['app_name'])){$this->error('上传文件有误');}
            }


            $next_info = Db::name('app_update')->where('id ='.$param['id'])->find();
            $this->empty_data($param['upgrade_point'],'更新备注不能为空');
        }else{
            $this->empty_data($param['iden'],'api标识不能为空');
            $this->empty_data($param['app_name1'],'名称不能为空');
            $this->empty_data($param['version_code1'],'版本号不能为空');

            $this->empty_data($param['upgrade_point'],'更新备注不能为空');

            if($param['type'] == 2){
                $this->empty_data($param['apk_url'],'版本更新地址不能为空');
                $sql_data['apk_url'] = $param['apk_url'];
            }
            $sql_data['app_name'] = $param['app_name1'];
            $sql_data['version_code'] = $param['version_code1'];

        }

        //重组数据准备入库
        $sql_data['upgrade_point'] = $param['upgrade_point'];
        $sql_data['force'] = isset($param['force'])?1:0;
        $sql_data['create_time'] = time();

        $status = Db::name('app_update')->where('id ='.$param['id'])->update($sql_data);  //
        //如果type等于1那么就把原来的包删除
        if(!empty($_FILES)){
            if($param['type'] == 1){
                if(!isset($param['apk_url'])) {
                    $this->del_apk($next_info);
                }
            }
        }
        $this->data_action($status,'add');
    }

    public function del(){
        $id = $this->data['id'];
        $info = Db::name('app_update')->where('id ='.$id)->find();
        if($info['apk_url']=='' || (is_file($info['apk_url']) && unlink(ROOT_PATH.'/public/upload/'.$info['apk_url']))){
            $status =  Db::name('app_update')->where('id ='.$id)->delete();
            $this->data_action($status,'del');
        }

    }

    public function setstatus(){
       unset($this->data['_plugin']);
       unset($this->data['_controller']);
       unset($this->data['_action']);
        $status = Db::name('app_update')->where('id ='.$this->data['id'])->update($this->data);
        $this->data_action($status,'update',cmf_plugin_url('QbtAppUpdate://AdminIndex/index'));
    }



    //判断入库状态
    public function data_action($status,$str){
        if($status !== false){
            if($str == 'add'){
                $this->success('保存成功！',cmf_plugin_url('QbtAppUpdate://AdminIndex/index'));
            }else if( $str == 'update'){
                $this->success('更改成功！',cmf_plugin_url('QbtAppUpdate://AdminIndex/index'));
            }else if($str == 'del'){
                $this->success('删除成功！',cmf_plugin_url('QbtAppUpdate://AdminIndex/index'));
            }
        }else{
            $this->error('操作失败！');
        }
    }

    //文件上传
    public function upload_app(){
        $file = request()->file('apk_url');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public/upload/apk/' . DS);
            if($info){
                // 成功上传后 获取上传信息
                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                return 'apk/'.$info->getSaveName();
            }else{
                // 上传失败获取错误信息
                $this->error($file->getError());
            }
        }
    }

    //获取apk文件信息
    public function app_info($filedir){
        //列出目录中的文件
        $info = [];
        if(!$this->apkarser->open($filedir)); //解析安装包
        $info['app_name'] = $this->apkarser->getAppName();     // 应用名称
        $info['packge_name'] = $this->apkarser->getPackage();    // 应用包名
        $info['version_name'] = $this->apkarser->getVersionName();  // 版本名称
        $info['version_code'] = $this->apkarser->getVersionCode();  // 版本代码
        return $info;
    }

    //判断数据是否为空
    public function empty_data($data,$str){
        if(empty($data)){
            $this->error($str);
        }
    }

    //判断数据是否在数据库存在
    public function have_data($data,$str){
       $info = Db::name('app_update')->where("iden = '$data'")->find();
       if(!empty($info)){$this->error($str);}
    }

    //判断文件是否存在
    public function isset_data($str){
        if(empty($_FILES)){
            $this->error($str);
        }
    }

    //如果type = 1，那么在添加成功之后就删除掉上一个版本的apk文件
    public function del_apk($info){
        if(!empty($info)){
            $apk_url = $info['apk_url'];

            unlink(ROOT_PATH.'/public/upload/'.$apk_url);
        }
    }

    //数据详情
    public function data_info($where){
        return Db::name('app_update')->where($where)->find();
    }


}
